/*
 * @Author: AiLjx
 * @Date: 2022-07-01 22:44:43
 * @LastEditors: AiLjx
 * @LastEditTime: 2022-07-01 22:55:06
 */
import { Navigate, useRoutes } from "react-router-dom";
import { lazy, Suspense } from "react";

// 使用useRoutes配置路由
export default function MRouter() {
    const element = useRoutes([
        {
            path: "/main",
            element: LazyLoad("Layout"),
            // 嵌套路由
            children: [
                {
                    path: "", // <Route index element={<Board />}></Route>
                    element: LazyLoad("layout/Board"),
                },
                {
                    path: "article",
                    element: LazyLoad("layout/Article"),
                },
            ],
        },
        {
            path: "/login",
            element: LazyLoad("Login"),
        },
        {
            path: "/about",
            element: LazyLoad("About"),
        },
        {
            path: "/about/:id",
            element: LazyLoad("About"),
        },
        {
            path: "/",
            element: <Navigate to='/main' />,
        },
        {
            path: "*",
            element: LazyLoad("NotFound"),
        },
    ]);
    return element;
}

// 封装组件懒加载
const LazyLoad = (path) => {
    // import中必须要有一个固定的前缀，直接import(path)不行
    const Comp = lazy(() => import(`../views/${path}`));
    return (
        <Suspense
            fallback={
                <div
                    style={{
                        textAlign: "center",
                        marginTop: 200,
                    }}>
                    loading...
                </div>
            }>
            <Comp></Comp>
        </Suspense>
    );
};
